<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\service\user;

use support\Cache;
use app\common\model\User;
use Wangpeng1208\Captcha\Captcha;
use Webman\Event\Event;
use Webman\RateLimiter\Limiter;

class UserService
{
    /**
     * 获取图形验证码
     */
    public function getCaptcha()
    {
        $captcha = new Captcha();
        return $captcha->base64([]);
    }

    /**
     * 检查图形验证码
     */
    public function checkCaptcha()
    {
        $post = request()->post();
        (new \app\userapi\validate\UserValidate)->data('captcha', $post);
    }

    /**
     * 注册邮箱验证码验证
     */
    private function email_code_check($email, $code)
    {
        $email_key  = str_replace('@', '_', $email);
        $code_cache = Cache::get('email_code_register_' . $email_key);
        if ($code_cache != $code) {
            throw new \Exception("邮箱验证码错误");
        }
    }

    /**
     * 注册
     * @return void
     */
    public function register()
    {
        // Limiter::check(request()->ip(), 1, 24 * 60 * 60, '您今日已注册过一次，请明日再来');
        try {
            $post = request()->post();
            $data = (new \app\userapi\validate\UserValidate)->data('register', $post);

            $data["password"] = password_hash($data["password"], PASSWORD_DEFAULT);
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
        User::create($data);
    }

    /**
     * 用户登录
     * @param $username
     * @param $password
     * @return array
     * @throws \Exception
     */
    public function login()
    {
        $loginType = inputs('loginType/s', 'passowrd');
        $data      = [
            'username'    => inputs('username/s', ''),
            'password'    => inputs('password/s', ''),
            'email_code'  => inputs('email_code/s', ''),
            'captcha'     => inputs('captcha/s', ''),
            'captcha_key' => inputs('captcha_key/s', ''),
        ];
        $validate  = new \app\userapi\validate\UserValidate;
        switch ($loginType) {
            case 'password':
                $validate->scene('loginByPassword')->failException(true)->check($data);
                break;
            case 'email_code':
                $validate->scene('loginByEmailCode')->failException(true)->check($data);
                break;
            default:
                throw new \Exception("登录方式错误");
        }

        $user = filter_var($data['username'], FILTER_VALIDATE_EMAIL) ? User::where(["email" => $data['username']])->find() : User::where(["username" => $data['username']])->find();

        if (empty($user)) {
            $accountType = filter_var($data['username'], FILTER_VALIDATE_EMAIL) ? '邮箱' : '用户名';
            throw new \Exception($accountType . "不存在!");
        }

        // 密码验证
        if ($loginType == 'password' && !password_verify($data['password'], $user->password)) {
            throw new \Exception("密码错误");
        }

        if ($loginType == 'email_code' && $this->email_code_check($data['username'], $data['email_code'])) {
            throw new \Exception("邮箱验证码错误");
        }

        if ($user->status == 0) {
            throw new \Exception("该账号状态异常");
        }
        return $this->loginSuccess($user);
    }

    /**
     * 用户登录成功
     * @param User $user
     * @return array
     * @throws \Exception
     */
    public function loginSuccess(User $user)
    {
        $user  = $user->toArray();
        $token = (new UserCommonService())->createToken($user, 'user');

        $allowFields = ['id', 'status', 'username', 'email'];
        $user        = array_intersect_key($user, array_flip($allowFields));

        // 登录成功后置事件
        Event::dispatch('user.login.success', $user);

        return array_merge($user, $token);
    }

    /**
     * 发送邮箱登录验证码
     */
    public function sendEmailCode()
    {
        $post = [
            'email'       => inputs('email/s', ''),
            'captcha'     => inputs('captcha_code/s', ''),
            'captcha_key' => inputs('captcha_id/s', ''),
        ];
        $data = (new \app\userapi\validate\UserValidate)->data('emailCode', $post);
        $code = rand(100000, 999999);
        EmailMessageService::send($data['email'], '邮箱验证码', '您的验证码为：' . $code);
        $email_key = str_replace('@', '_', $data['email']);
        Cache::set('email_code_register_' . $email_key, $code, 300);
    }
}